<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace yiike\user\models;

use Yii;
use dektrium\user\clients\ClientInterface;
use yii\authclient\ClientInterface as BaseClientInterface;
use dektrium\user\models\User;
/**
 * Description of Account
 *
 * @author Sylar
 */
class Account extends \dektrium\user\models\Account{
    
    public static function create(BaseClientInterface $client)
    {
        $attributes = $client->getUserAttributes();
        /** @var Account $account */
        $account = Yii::createObject([
            'class'      => static::className(),
            'provider'   => $client->getId(),
            'client_id'  => $attributes['id'],
            'unionid'    => isset($attributes['unionid']) ? $attributes['unionid'] : null,
            'data'       => json_encode($attributes, JSON_UNESCAPED_UNICODE),
        ]);


        if ($client instanceof ClientInterface) {
            $account->setAttributes([
                'username' => $client->getUsername(),
                'email'    => $client->getEmail(),
            ], false);
        }

        if (($user = parent::fetchUser($account)) instanceof User) {
            $account->user_id = $user->id;
        }

        $account->save(false);

        return $account;
    }
    /**
     * Tries to find an account and then connect that account with current user.
     *
     * @param BaseClientInterface $client
     */
    public static function connectWithUser(BaseClientInterface $client)
    {
        if (\Yii::$app->user->isGuest) {
            \Yii::$app->session->setFlash('danger', \Yii::t('user', 'Something went wrong'));

            return false;
        }

        $account = parent::fetchAccount($client);

        if ($account->user === null) {
            $account->link('user', \Yii::$app->user->identity);
            return true;
        } else {
            $account->user_id = Yii::$app->user->id;
            return $account->save();
        }
    }
}
